"use client"
import classNames from "classnames"
import { MyFormModal, MyFormModalBody, MyFormModalContent, MyFormModalFooter, MyFormModalHeader, MyFormModalTrigger,  } from "../my-form-modal"
import "./style.css"
import { useState, useEffect, useImperativeHandle, forwardRef, JSX } from "react"
import { List, ListContent } from "@/components/common/list"
import Icon from "@/components/common/icon"
import { X } from "lucide-react"
import { FaAngleDown, FaCheck } from "react-icons/fa6";
import MyButton from "../my-button"
import { Checkbox } from "@/components/ui/checkbox"

type ValueType<T extends boolean> = T extends true? string[] : string

interface Props<T extends boolean = false> {
  placeholder?: string
  value?: ValueType<T>
  onChange: (value: ValueType<T>)=>void
  header?: string
  options: {
    label: string
    value: string
  }[]
  multiple?: T;
}

export interface MySelectRef<T extends boolean = false> {
  tempValue: ValueType<T>;
}

const MySelect = <T extends boolean = false>({
  value, 
  onChange, 
  options, 
  placeholder, 
  header, 
  multiple
}: Props<T>, ref: React.Ref<MySelectRef<T>>) => {
  const [open, setOpen] = useState(false)
  const [tempValue, setTempValue] = useState<ValueType<T>>(value as ValueType<T>)

  // 暴露 tempValue 给父组件
  useImperativeHandle(ref, () => ({
    tempValue
  }), [tempValue])

  // 当弹窗打开时，初始化临时值
  useEffect(() => {
    if (open) {
      setTempValue(value as ValueType<T>)
    }
  }, [open, value])

  // 获取当前选中的选项（用于显示）- 使用外部 value 而不是 tempValue
  const getSelectedOptions = () => {
    if (multiple) {
      const values = value as string[]
      return options.filter(item => values?.includes(item.value))
    } else {
      const singleValue = value as string
      return options.filter(item => item.value === singleValue)
    }
  }

  const selectedOptions = getSelectedOptions()
  const isSelected = multiple ? (selectedOptions.length > 0) : !!selectedOptions[0]

  // 显示文本 - 使用外部 value 而不是 tempValue
  const getDisplayText = () => {
    if (!isSelected) return placeholder
    
    if (multiple) {
      return selectedOptions.length > 0 
        ? `${selectedOptions?.[0].label}${selectedOptions.length > 1 ? ` (+${selectedOptions.length - 1})` : ''}` 
        : placeholder
    } else {
      return selectedOptions[0]?.label || placeholder
    }
  }

  // 切换选项选中状态（仅更新临时值，不触发外部 onChange）
  const toggleOption = (optionValue: string) => {
    if (multiple) {
      // 使用类型断言明确告诉 TypeScript 这是 string 数组
      const currentValues = (Array.isArray(tempValue) ? tempValue : []) as string[]
      const newValues = currentValues.includes(optionValue)
        ? currentValues.filter(v => v !== optionValue)
        : [...currentValues, optionValue]
      setTempValue(newValues as ValueType<T>)
    } else {
      // 单选模式下直接更新并关闭
      setTempValue(optionValue as ValueType<T>)
      onChange(optionValue as ValueType<T>)
      setOpen(false)
    }
  }

  // 确定选择（仅用于多选）- 点击确定后才更新外部状态
  const handleConfirm = () => {
    onChange(tempValue)
    setOpen(false)
  }

  // 清除选择（仅用于多选弹窗内）- 只清除临时值
  const handleClear = () => {
    if (multiple) {
      setTempValue([] as unknown as ValueType<T>)
    } else {
      setTempValue('' as ValueType<T>)
    }
  }

  // 清除按钮点击（在触发器上）- 直接清除外部状态
  const handleClearTrigger = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (multiple) {
      onChange([] as unknown as ValueType<T>)
    } else {
      onChange('' as ValueType<T>)
    }
  }

  // 检查选项是否被选中（使用临时值）
  const isOptionSelected = (optionValue: string) => {
    if (multiple) {
      return Array.isArray(tempValue) && (tempValue as string[]).includes(optionValue)
    } else {
      return tempValue === optionValue
    }
  }

  return ( 
    <MyFormModal setOpen={setOpen} open={open} >
      <MyFormModalTrigger>
        <div className={classNames("my-select flex items-center gap-content-gap-x md:gap-content-gap-x-md", {
          'active': open,
          'placeholder': !isSelected
        })}>
          {/* 内容 - 显示的是外部 value 的状态 */}
          <span>{getDisplayText()}</span>
          {/* 清除按钮 */}
          {isSelected ? (
            <button onClick={handleClearTrigger} className="bg-secondary p-1 rounded-full">
              <Icon size="small" icon={X} />
            </button>
          ) : null}
          {/* 箭头指示器 */}
          <Icon size="small" className={classNames({
            'rotate-180 transition-transform duration-200': open,
          })} icon={FaAngleDown} />
        </div>
      </MyFormModalTrigger>
      <MyFormModalContent>
        {header ? <MyFormModalHeader>{header}</MyFormModalHeader> : null}
        <MyFormModalBody>
          <List>
            {options.map(item => (
              <ListContent 
                className={classNames("flex items-center cursor-pointer")} 
                onClick={() => toggleOption(item.value)} 
                key={item.value}
              >
                {
                  multiple? (
                    <div className="flex items-center gap-content-gap-x md:gap-card-gap-x-md w-full">
                      <Checkbox 
                        checked={isOptionSelected(item.value)} 
                        onCheckedChange={() => toggleOption(item.value)}
                      /> 
                      <span>{item.label}</span>
                    </div>
                  ) : (
                    <div className="flex items-center justify-between w-full">
                      <span>{item.label}</span>
                      {isOptionSelected(item.value) ? <Icon className="text-primary" size="small" icon={FaCheck} /> : null}
                    </div>
                  )
                }
              </ListContent>
            ))}
          </List>
        </MyFormModalBody>
        {/* 只在多选模式下显示底部按钮 */}
        {multiple && (
          <MyFormModalFooter className={'flex flex-row gap-x-card-gap-x md:gap-x-card-gap-x-md'}>
            <MyButton 
              className="flex-1" 
              variant="secondary" 
              onClick={handleClear}
            >
              清除
            </MyButton>
            <MyButton 
              className="flex-1" 
              onClick={handleConfirm}
            >
              确定
            </MyButton>
          </MyFormModalFooter>
        )}
      </MyFormModalContent>
    </MyFormModal>
  )
}

// 使用 forwardRef 包装组件
export default forwardRef(MySelect) as <T extends boolean = false>(
  props: Props<T> & { ref?: React.Ref<MySelectRef<T>> }
) => JSX.Element